home *** CD-ROM | disk | FTP | other *** search
- Path: news.clark.net!not-for-mail
- From: gusty@clark.net (Harlan Messinger)
- Newsgroups: comp.lang.c++
- Subject: Re: Proper use of friend keyword
- Date: 2 Apr 1996 15:39:00 GMT
- Organization: Clark Internet Services, Inc., Ellicott City, MD USA
- Message-ID: <4jrhmk$kdl@clarknet.clark.net>
- References: <4jn38u$j9c@holly.ACNS.ColoState.EDU>
- NNTP-Posting-Host: explorer.clark.net
- Mime-Version: 1.0
- Content-Type: TEXT/PLAIN; charset=ISO-8859-1
- Content-Transfer-Encoding: 8bit
- X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
-
- Corby S. Hudnall (corbyh@holly.ACNS.ColoState.EDU) wrote:
- : Hey all, I have a question about how to use the friend keyword. Consider
- : the following example:
-
- The purpose of the friend keyword is to allow some or all of the
- member functions of select classes to use directly members of another
- class that are private or protected within that class. When you write
-
- : friend int ABC::GetAValue();
-
- inside of the definition of XYZ, you are saying that the body of
- ABC::GetAValue() may directly access protected and private members of an
- XYZ object--that is, members that are ordinarily hidden from outside
- classes--AS members of ABC. It does not create a member function
- GetAValue() within XYZ.
-
- Friend functions and classes should be used carefully. The only situation
- where one class should be using another class's hidden members is when the
- two classes really are working together as a cohesive unit that
- theoretically could or should be encapsulated in ONE class, except that
- the syntax of the language doesn't permit it, or the classes are not in
- one-to-one correspondence.
-
- A definition of XYZ that would use friend properly might be:
-
- class XYZ
- {
- ABC myABC;
- public:
- XYZ() { }
- ~XYZ() { }
- friend int ABC::GetAValue();
- void processMyABC();
- };
-
- void XYZ::processMyABC()
- {
- myABC.GetAValue();
- }
-
- If XYZ wasn't a friend of ABC::GetAValue(), it wouldn't be able to make
- this call to myABC.GetAValue() because ABC::GetAValue() is private to ABC.
-